import { Text, View, StyleSheet, TouchableWithoutFeedback, FlatList, Image, Clipboard } from 'react-native'
import React, { Component, useState, useEffect } from 'react'
import { connect } from 'react-redux'
import { asyncGetGroupList, SetGroupMsg } from "../../redux/features/appSlice"
import { pTx } from "../../utils/dimensions"
import { Cell, Badge } from '@pingtou/rn-vant'
import { formatGroupMsg } from "../../utils/formatFriendMsg"
import httpApi from "../../api"
import { showModal } from "../../components/rootSiblings/showModal"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm from "realm"
import DeleteContact from "../../components/rootSiblings/deleteContact"
import Avatar from "../../components/avatar"
import realmValue from "../../utils/realmValue"
import IconFont from '@pingtou/rn-vant-icons'
import { Toast } from '@ant-design/react-native'

const GroupInfoMaterial = (props) => {
    const [group] = useState(props.route.params)
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];

    const groupList = useQuery(schemaName.GroupList, Group => {
        return Group.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`);
    })

    const groupInfo = useQuery(schemaName.GroupInfo, Info => {
        return Info.filtered(`Id == ${group.G} and UserId == ${userInfo.Id}`);
    })[0];

    const groupMembers = useQuery(schemaName.GroupMembers, groupMsg => {
        return groupMsg.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`)
    })

    const groupMsgLis = useQuery(schemaName.GroupMsgLis, groupMsg => {
        return groupMsg.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`).sorted('T', true)
    })

    const groupAdmins = useQuery(schemaName.GroupAdmins, admins => {
        return admins.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`)
    })

    const isAdmins = () => userInfo.Id == groupInfo?.OwnerId

    const groupMsgLisJoinUnread = groupMsgLis.filtered(`G == ${group.G} and UserId == ${userInfo.Id} and MT == 61 and  Unread == 1`)

    useEffect(() => {
        props.navigation.setOptions({
            headerTitle: ({ options }) => (
                <Text style={styles.headerTitle} ellipsizeMode={'tail'} numberOfLines={1}>聊天信息({groupInfo?.Num})</Text>
            ),
        });
    })

    const sendGroupRemoveSelf = async () => {
        try {
            const res = await httpApi.sendGroupRemoveSelf({ groupId: group.G })
            if (res.code == 20) {
                props.navigation.navigate('chat')
                setTimeout(() => {
                    realm.write(() => {
                        realm.delete(groupList);
                        realm.delete(groupMembers);
                        realm.delete(groupMsgLis);
                    })
                })
            }
        } catch (error) {
        }
    }
    const copyToClipboard = () => {
        Clipboard.setString(groupInfo.Address)
        Toast.info('复制成功')
    }
    return (
        <View style={styles.page}>
            <View >
                <FlatList
                    renderItem={({ item, index }) => {
                        switch (item.type) {
                            case 1:
                                return <TouchableWithoutFeedback onPress={() => props.navigation.navigate('groupInvite', group)}><View style={styles.FlatListItem} >
                                    <Image style={styles.Avatar} source={require('../../assets/image/icon50-add.png')}></Image>
                                    <Text style={styles.userName} ellipsizeMode={'tail'} numberOfLines={1}></Text>
                                </View>
                                </TouchableWithoutFeedback>
                            case 2:

                                return <TouchableWithoutFeedback onPress={() => props.navigation.navigate('groupRemove', group)}><View style={styles.FlatListItem} >
                                    <Image style={styles.Avatar} source={require('../../assets/image/icon50.png')}></Image>
                                    <Text style={styles.userName} ellipsizeMode={'tail'} numberOfLines={1}></Text>
                                </View>
                                </TouchableWithoutFeedback>

                            default:
                                return <View style={styles.FlatListItem}>
                                    <Avatar style={styles.Avatar} source={{ uri: item.P }} />
                                    <Text style={styles.userName} ellipsizeMode={'tail'} numberOfLines={1}>{item.R}</Text>
                                </View>
                        }

                    }}
                    columnWrapperStyle={{ justifyContent: "flex-start", }}
                    data={(!!groupAdmins.find(item => item.Id == userInfo.Id) || isAdmins()) ? [...groupMembers, { type: 1 }, { type: 2 }] : [...groupMembers, { type: 1 }]}
                    numColumns={5}
                    keyExtractor={(item, index) => index}
                />
            </View>
            <View style={{ marginTop: pTx(10) }}>
                <Cell.Group>
                    <Cell title="群聊名称" value={
                        <View style={styles.right}>
                            <Text >{groupInfo?.GroupName}</Text>
                            {isAdmins() && <IconFont name="arrow" size={pTx(16)} />}
                        </View>
                    } onPress={() => props.navigation.navigate('groupName', group)} />
                    <Cell title="群聊头像" center value={
                        <View style={styles.right}>
                            <Avatar style={styles.Avatar} source={{ uri: groupInfo?.Logo }} />
                            {isAdmins() && <IconFont name="arrow" size={pTx(16)} />}
                        </View>
                    } onPress={() => isAdmins() && props.navigation.navigate('groupLogo', group)} />
                    <Cell title="群地址" value={
                        <View style={styles.right}>
                            <Text style={styles.address} ellipsizeMode={'tail'} numberOfLines={1}>{groupInfo?.Address}</Text>
                            {isAdmins() && <IconFont name="arrow" size={pTx(16)} />}
                        </View>
                    } onPress={() => copyToClipboard()} />
                    <Cell title="群聊公告" center value={
                        <View style={styles.right}>
                            {isAdmins() && <IconFont name="arrow" size={pTx(16)} />}
                        </View>
                    }
                        label={groupInfo?.Notice ? <Text >{groupInfo?.Notice}</Text> : false}
                        onPress={() => isAdmins() && props.navigation.navigate('groupNotice', group)} />

                    {(!!groupAdmins.find(item => item.Id == userInfo.Id) || isAdmins()) && <Cell title="群管理" value={
                        <View style={styles.right}>
                            {groupMsgLisJoinUnread.length > 0 && <Badge dot={!!groupMsgLisJoinUnread.length} />}
                            {!!groupAdmins.find(item => item.Id == userInfo.Id) || isAdmins() && <IconFont name="arrow" size={pTx(16)} />}
                        </View>
                    } onPress={() => (!!groupAdmins.find(item => item.Id == userInfo.Id) || isAdmins()) && props.navigation.navigate('groupManage', group)} />}
                </Cell.Group>
            </View>
            <View style={styles.foot}>
                <TouchableWithoutFeedback
                    disabled={userInfo.Id == groupInfo?.OwnerId}
                    onPress={() => showModal(<DeleteContact operation={
                        [
                            { text: '退出群聊', onPress: () => sendGroupRemoveSelf() },
                        ]
                    } />)}
                >
                    <View style={[styles.footRow, { opacity: userInfo.Id == groupInfo?.OwnerId ? 0.5 : 1 }]}>
                        <Text style={styles.sendMessage} >退出群聊</Text>
                    </View>
                </TouchableWithoutFeedback>
            </View>
        </View>
    )
}

const mapStateToProps = (state) => state.app

const mapDispatchToProps = {
    asyncGetGroupList,
    SetGroupMsg
}

export default connect(mapStateToProps, mapDispatchToProps)(GroupInfoMaterial)

const styles = StyleSheet.create({
    headerRightIcon: {
        paddingRight: pTx(15),
    },
    page: {
        flex: 1,
        backgroundColor: "#EDEDED"
    },
    FlatListItem: {
        paddingHorizontal: pTx(12),
        paddingVertical: pTx(6),
        alignSelf: "center"
    },
    Avatar: {
        width: pTx(50),
        height: pTx(50),
        borderRadius: pTx(4),
    },
    userName: {
        textAlign: "center",
        width: pTx(50),
    },
    foot: {
        marginTop: pTx(10),
        backgroundColor: "#ffffff"
    },
    footRow: {
        height: pTx(50),
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center"
    },
    sendMessage: {
        marginLeft: pTx(3),
        fontSize: pTx(16),
        color: "#ee0a24",
        textAlign: "center"
    },
    setUp: {
        paddingHorizontal: pTx(10),
        paddingVertical: pTx(5),
        backgroundColor: 'rgba(0,0,0,0.1)',
        borderRadius: pTx(5),
    },
    styleText: {
        marginLeft: pTx(3),
        fontSize: pTx(12),
    },
    applyMsg: {
        minWidth: pTx(18),
        paddingHorizontal: pTx(5),
        paddingVertical: pTx(1),
        borderRadius: pTx(38),
        textAlign: "center",
        color: "#fff",
        fontWeight: "500",
        fontSize: pTx(10),
        backgroundColor: "#ee0a24"
    },
    right: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center"
    },
    address: {
        maxWidth: pTx(200),
    }
})